import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store'
import { h } from 'vue'
// 路由规则
const routes = [
  // 一级路由布局容器
  {
    path: '/',
    component: () => import('@/views/Layout.vue'),
    children: [
      { path: '/', component: () => import('@/views/home') },
      { path: '/category/:id', component: () => import('@/views/category') },
      { path: '/category/sub/:id', component: () => import('@/views/category/sub') },
      { path: '/product/:id', component: () => import('@/views/goods') },
      { path: '/cart', component: () => import('@/views/cart') },
      { path: '/member/checkout', component: () => import('@/views/member/pay/checkout') },
      { path: '/member/pay', component: () => import('@/views/member/pay') },
      { path: '/pay/callback', component: () => import('@/views/member/pay/result') },
      {
        path: '/member',
        component: () => import('@/views/member/Layout'),
        children: [
          { path: '/member', component: () => import('@/views/member/home') },
          // { path: '/member/order', component: () => import('@/views/member/order') },
          // { path: '/member/order/:id', component: () => import('@/views/member/order/detail') }
          {
            path: '/member/order',
            // 创建一个 RouterView 容器形成嵌套关系
            component: { render: () => h(<RouterView/>) },
            children: [
              { path: '', component: () => import('@/views/member/order') },
              { path: ':id', component: () => import('@/views/member/order/detail') }
            ]
          }
        ]
      }
    ]
  },
  { path: '/login', component: () => import('@/views/login') },
  { path: '/login/callback', component: () => import('@/views/login/callback') }
]
// vue2.0 new vueRoutes({}) 创建路由实例
// vue3.0 createRouter({})
const router = createRouter({
  // 使用hash的路由模式
  history: createWebHashHistory(),
  routes,
  // 每次切换路由时候滚动到页面顶部
  scrollBehavior () {
    // vue2.0 x y 控制
    // vue3.0 left top 控制
    return { left: 0, top: 0 }
  }
})
// 前置导航守卫
router.beforeEach((to, from, next) => {
  // 需要登录的路由：地址是以 /member 开头
  const { profile } = store.state.user
  if (!profile.token && to.path.startsWith('/member')) {
    return next(`/login?redirectUrl=${encodeURIComponent(to.fullPath)}`)
  }
  next()
})
export default router
